package com.liu.dao.impl;
import com.liu.Bean.User;
import com.liu.dao.UserDao;
import com.liu.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaolmpl implements UserDao {
    Connection con = null;
    User user = null;
    PreparedStatement pstm = null;
    ResultSet rs = null;
    int row = 0;
    //登录
    public User Login(String username,String password){
        con = JDBCUtil.getCon();
        String sql = "select * from users where username = ? and password = ?";
        try {
            pstm = con.prepareStatement(sql);
            pstm.setObject(1,username);
            pstm.setObject(2,password);

            rs = pstm.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("uid"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.colse(rs,pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }
    //注册用户
    public  int register(User user){
        con = JDBCUtil.getCon();
        String sql = "insert into users(username,email,password)value(?,?,?)";
        try {
            pstm = con.prepareStatement(sql);
            pstm.setObject(1,user.getUsername());
            pstm.setObject(2,user.getEmail());
            pstm.setObject(3,user.getPassword());
            row = pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.colse(pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return row;
    }
    //删除用户信息
    public int shanchu(int id){
        con = JDBCUtil.getCon();
        String sql = "delete from users where id = ?";
        try {
            pstm = con.prepareStatement(sql);
            pstm.setObject(1,id);
            row = pstm.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                JDBCUtil.colse(pstm,con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(row);
        return row;
    }
}
